import axios from 'axios'
import qs from 'qs'
import { message, Modal } from 'ant-design-vue'
import { handlelangs } from '../utils/tool'
import { codesCN, codesEN, codesCNTW } from '../assets/JSdata/request'
import { requestConfig } from '../config'
import  router from '../router'

let Colleague = true;

function defend(code) {
    //判断是过期
    if (code == '701' || code == '401') {
        //不弹框提示
        Colleague = true;
        window.sessionStorage.removeItem('Authorization');
        window.localStorage.clear();
        router.push({path: "/login", query: {
                //lastPath: router.history.current.path //返回上一次页面
                lastPath: '/'
            }});

        /*Colleague = false;
        let {title, content, okText, cancelText} = new Map(handlelangs() === 'cn' ? codesCN : handlelangs() === 'en' ? codesEN : codesCNTW).get(code);
        Modal.confirm({
            title,
            content,
            okText,
            okType: 'primary',
            cancelText,
            onOk() {
                Colleague = true;
                window.sessionStorage.removeItem('Authorization');
                window.localStorage.clear();
                router.push({path: "/login", query: {
                     lastPath: router.history.current.path
                }});
            },
            onCancel() {
                Colleague = true;
            }
        });*/
    }else {
        message.warning(new Map(handlelangs() === 'cn' ? codesCN : handlelangs() === 'en' ? codesEN : codesCNTW).get(code), 2.5);
    }
}

axios.defaults.timeout = 80000; //请求超时
axios.defaults.retryDelay = 1000; //请求间隔
// 创建 axios 实例
const service = axios.create(requestConfig);

// 添加请求拦截器
service.interceptors.request.use(function (config) {
    if(!Colleague && config.url.includes('/sys/getUserByCompany')) {
        return false
    }
    if (config.url) {
        config.headers.common['Authorization'] = window.sessionStorage.getItem('Authorization');
        if (window.localStorage.getItem('userId')) {
        config.headers.common['USER'] = JSON.parse(window.localStorage.getItem('userId'));
        }
    }
    // 在发送请求之前做些什么
    if (config.method === 'post' || config.method === 'put') {
        config.headers.post['Content-Type'] = 'application/json'
    }
    if(config.method === 'get') {
            //如果是get请求，且params是数组类型如arr=[1, 2]，则转换成arr=1&arr=2
        config.paramsSerializer = function (params) {
                return qs.stringify(params, {arrayFormat: 'repeat'})
        }
    }
  return config
}, function (error) {
  return Promise.reject(error)
});



// 添加响应拦截器
service.interceptors.response.use(response => {
  const res = response.data;
  let code = res.code || 200; //没有Code值默认不弹框

  if(Colleague) {
      if(code != '200') {
          defend(code)
      }
  }
  return response
},  error => {
    const response = error.response || {}
    let { code } = response.data || {}

    //是否发起弹框
    if (Colleague) {
        //是否获取code
        if (code) {
            defend(code)
        }else {
            message.warning('服务器开小差了')
        }
    }
    return Promise.reject(error)
});

export default service
